#include "basic_configuration_validator.h"
#include <QDebug>

namespace infrastructure {

BasicConfigurationValidator::BasicConfigurationValidator() {
}

ValidationResult BasicConfigurationValidator::validate(const QHash<QString, QVariant>& configData) {
    ValidationResult result(true);
    
    for (const ValidationRule& rule : m_rules) {
        bool isValid = false;
        QString errorMessage;
        
        switch (rule.type) {
            case ValidationRuleType::Required:
                isValid = validateRequired(rule.key, configData);
                if (!isValid) {
                    errorMessage = rule.message.isEmpty() ? 
                        generateDefaultMessage(rule) : rule.message;
                }
                break;
                
            case ValidationRuleType::TypeCheck:
                if (configData.contains(rule.key)) {
                    isValid = validateType(rule, configData.value(rule.key));
                    if (!isValid) {
                        errorMessage = rule.message.isEmpty() ? 
                            generateDefaultMessage(rule) : rule.message;
                    }
                } else {
                    isValid = true; // 如果键不存在，类型检查跳过
                }
                break;
                
            case ValidationRuleType::Range:
                if (configData.contains(rule.key)) {
                    isValid = validateRange(rule, configData.value(rule.key));
                    if (!isValid) {
                        errorMessage = rule.message.isEmpty() ? 
                            generateDefaultMessage(rule) : rule.message;
                    }
                } else {
                    isValid = true; // 如果键不存在，范围检查跳过
                }
                break;
                
            case ValidationRuleType::Length:
                if (configData.contains(rule.key)) {
                    isValid = validateLength(rule, configData.value(rule.key));
                    if (!isValid) {
                        errorMessage = rule.message.isEmpty() ? 
                            generateDefaultMessage(rule) : rule.message;
                    }
                } else {
                    isValid = true; // 如果键不存在，长度检查跳过
                }
                break;
                
            case ValidationRuleType::Pattern:
                if (configData.contains(rule.key)) {
                    isValid = validatePattern(rule, configData.value(rule.key));
                    if (!isValid) {
                        errorMessage = rule.message.isEmpty() ? 
                            generateDefaultMessage(rule) : rule.message;
                    }
                } else {
                    isValid = true; // 如果键不存在，模式检查跳过
                }
                break;
                
            case ValidationRuleType::Custom:
                if (configData.contains(rule.key)) {
                    isValid = validateCustom(rule, configData.value(rule.key));
                    if (!isValid) {
                        errorMessage = rule.message.isEmpty() ? 
                            generateDefaultMessage(rule) : rule.message;
                    }
                } else {
                    isValid = true; // 如果键不存在，自定义检查跳过
                }
                break;
        }
        
        if (!isValid) {
            result.addError(rule.key, errorMessage, rule.severity);
        }
    }
    
    return result;
}

QString BasicConfigurationValidator::getName() const {
    return "BasicConfigurationValidator";
}

QString BasicConfigurationValidator::getDescription() const {
    return QString("基本配置验证器 - 包含 %1 个验证规则").arg(m_rules.size());
}

void BasicConfigurationValidator::addRequiredKey(const QString& key, const QString& message, const QString& severity) {
    ValidationRule rule;
    rule.key = key;
    rule.type = ValidationRuleType::Required;
    rule.message = message;
    rule.severity = severity;
    addRule(rule);
}

void BasicConfigurationValidator::addTypeCheck(const QString& key, QVariant::Type expectedType, const QString& message, const QString& severity) {
    ValidationRule rule;
    rule.key = key;
    rule.type = ValidationRuleType::TypeCheck;
    rule.expectedValue = QVariant(expectedType);
    rule.message = message;
    rule.severity = severity;
    addRule(rule);
}

void BasicConfigurationValidator::addRangeCheck(const QString& key, const QVariant& min, const QVariant& max, const QString& message, const QString& severity) {
    ValidationRule rule;
    rule.key = key;
    rule.type = ValidationRuleType::Range;
    rule.expectedValue = min;
    rule.additionalValue = max;
    rule.message = message;
    rule.severity = severity;
    addRule(rule);
}

void BasicConfigurationValidator::addLengthCheck(const QString& key, int minLength, int maxLength, const QString& message, const QString& severity) {
    ValidationRule rule;
    rule.key = key;
    rule.type = ValidationRuleType::Length;
    rule.expectedValue = minLength;
    rule.additionalValue = maxLength;
    rule.message = message;
    rule.severity = severity;
    addRule(rule);
}

void BasicConfigurationValidator::addPatternCheck(const QString& key, const QString& pattern, const QString& message, const QString& severity) {
    ValidationRule rule;
    rule.key = key;
    rule.type = ValidationRuleType::Pattern;
    rule.pattern = pattern;
    rule.message = message;
    rule.severity = severity;
    addRule(rule);
}

void BasicConfigurationValidator::addCustomCheck(const QString& key, std::function<bool(const QVariant&)> validator, const QString& message, const QString& severity) {
    ValidationRule rule;
    rule.key = key;
    rule.type = ValidationRuleType::Custom;
    rule.customValidator = validator;
    rule.message = message;
    rule.severity = severity;
    addRule(rule);
}

void BasicConfigurationValidator::addRule(const ValidationRule& rule) {
    m_rules.append(rule);
}

void BasicConfigurationValidator::removeRule(const QString& key, ValidationRuleType type) {
    m_rules.erase(
        std::remove_if(m_rules.begin(), m_rules.end(),
                      [&key, type](const ValidationRule& rule) {
                          return rule.key == key && rule.type == type;
                      }),
        m_rules.end());
}

void BasicConfigurationValidator::clearRules() {
    m_rules.clear();
}

QVector<ValidationRule> BasicConfigurationValidator::getRules() const {
    return m_rules;
}

bool BasicConfigurationValidator::validateRequired(const QString& key, const QHash<QString, QVariant>& configData) {
    return configData.contains(key) && !configData.value(key).toString().isEmpty();
}

bool BasicConfigurationValidator::validateType(const ValidationRule& rule, const QVariant& value) {
    QVariant::Type expectedType = static_cast<QVariant::Type>(rule.expectedValue.toInt());
    return value.type() == expectedType || value.canConvert(expectedType);
}

bool BasicConfigurationValidator::validateRange(const ValidationRule& rule, const QVariant& value) {
    bool ok1, ok2;
    double val = value.toDouble(&ok1);
    if (!ok1) return false;
    
    double min = rule.expectedValue.toDouble(&ok1);
    double max = rule.additionalValue.toDouble(&ok2);
    
    if (!ok1 || !ok2) return false;
    
    return val >= min && val <= max;
}

bool BasicConfigurationValidator::validateLength(const ValidationRule& rule, const QVariant& value) {
    QString str = value.toString();
    int length = str.length();
    int minLength = rule.expectedValue.toInt();
    int maxLength = rule.additionalValue.toInt();
    
    return length >= minLength && length <= maxLength;
}

bool BasicConfigurationValidator::validatePattern(const ValidationRule& rule, const QVariant& value) {
    QString str = value.toString();
    QRegularExpression regex(rule.pattern);
    return regex.match(str).hasMatch();
}

bool BasicConfigurationValidator::validateCustom(const ValidationRule& rule, const QVariant& value) {
    if (!rule.customValidator) {
        return true;
    }
    
    try {
        return rule.customValidator(value);
    } catch (const std::exception& e) {
        qWarning() << "自定义验证函数执行失败:" << e.what();
        return false;
    }
}

QString BasicConfigurationValidator::generateDefaultMessage(const ValidationRule& rule) const {
    switch (rule.type) {
        case ValidationRuleType::Required:
            return QString("配置键 '%1' 是必需的").arg(rule.key);
            
        case ValidationRuleType::TypeCheck:
            return QString("配置键 '%1' 的类型不正确").arg(rule.key);
            
        case ValidationRuleType::Range:
            return QString("配置键 '%1' 的值不在有效范围内 [%2, %3]")
                .arg(rule.key)
                .arg(rule.expectedValue.toString())
                .arg(rule.additionalValue.toString());
                
        case ValidationRuleType::Length:
            return QString("配置键 '%1' 的长度不在有效范围内 [%2, %3]")
                .arg(rule.key)
                .arg(rule.expectedValue.toInt())
                .arg(rule.additionalValue.toInt());
                
        case ValidationRuleType::Pattern:
            return QString("配置键 '%1' 的值不匹配模式 '%2'")
                .arg(rule.key)
                .arg(rule.pattern);
                
        case ValidationRuleType::Custom:
            return QString("配置键 '%1' 未通过自定义验证").arg(rule.key);
            
        default:
            return QString("配置键 '%1' 验证失败").arg(rule.key);
    }
}

} // namespace infrastructure 